package com.mdd.common.mapper.system;

import com.mdd.common.core.basics.IBaseMapper;
import com.mdd.common.entity.system.CouponReceive;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

/**
 * 领取记录Mapper
 * @author panweiliang
 */
@Mapper
public interface CouponReceiveMapper extends IBaseMapper<CouponReceive> {

    @Select({"SELECT COUNT(receive.id) AS couponCount FROM ls_coupon coupon INNER JOIN ls_coupon_receive receive ON coupon.id = receive.coupon_id WHERE receive.status = #{status} AND coupon.delete_time IS NULL "})
    Long countByStatus(@Param("status") Integer status);

    @Select({"SELECT COUNT(receive.id) AS couponCount FROM ls_coupon coupon INNER JOIN ls_coupon_receive receive ON coupon.id = receive.coupon_id WHERE receive.status = #{status} AND receive.user_id = #{userId} AND coupon.status = 2 AND coupon.delete_time IS NULL "})
    Long countByStatusAndUserId(@Param("status") Integer status, @Param("userId") Integer userId);

    @Select({"SELECT COUNT(receive.id) AS couponCount FROM ls_coupon coupon INNER JOIN ls_coupon_receive receive ON coupon.id = receive.coupon_id WHERE coupon.delete_time IS NULL "})
    Long countAll();

    @Select({"SELECT COUNT(receive.id) AS couponCount FROM ls_coupon coupon INNER JOIN ls_coupon_receive receive ON coupon.id = receive.coupon_id WHERE coupon.delete_time IS NULL AND receive.status = 0 AND coupon.status = 2 AND receive.user_id=#{userId}"})
    Long countUsedByUserId(@Param("userId") Integer userId);

    @Select({"SELECT receive.* FROM ls_coupon coupon INNER JOIN ls_coupon_receive receive ON coupon.id = receive.coupon_id WHERE coupon.delete_time IS NULL AND receive.status = #{status}"})
    List<CouponReceive> getByStatus(@Param("status") Integer status);

    @Update({"UPDATE ls_coupon_receive SET status = -1 WHERE expire_time <= #{curTime} AND status = 0"})
    void expire(@Param("curTime") Long curTime);

    @Select({"SELECT COUNT(receive.id) AS couponCount FROM ls_coupon coupon INNER JOIN ls_coupon_receive receive ON coupon.id = receive.coupon_id WHERE receive.user_id = #{userId} AND coupon.id = #{couponId} AND coupon.delete_time IS NULL "})
    Integer countByUserIdAndCouponId(@Param("userId") Integer userId, @Param("couponId") Integer couponId);

    @Select({"SELECT COUNT(receive.id) AS couponCount FROM ls_coupon coupon INNER JOIN ls_coupon_receive receive ON coupon.id = receive.coupon_id WHERE receive.user_id = #{userId} AND coupon.id = #{couponId} AND receive.receive_time >= #{startTime} AND receive.receive_time <= #{endTime} AND coupon.delete_time IS NULL "})
    Integer countDaliyByUserIdAndCouponId(@Param("userId") Integer userId, @Param("couponId") Integer couponId, @Param("startTime") Long startTime, @Param("endTime") Long endTime);
}
